package com.example.edu.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.util.Locale;

/**
 * @author yanzhao
 * @date 2022/1/15 23:11
 * @since 1.0.0
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * LocaleResolver是SessionLocaleResolver实例时，LocaleChangeInterceptor#setParamName生效，
     * 此时在请求地址上加上参数即可，如
     * interceptor.setParamName("lang");
     * 请求地址为{{url}}/api/v1.0/dependency/1?lang=zh
     * 如果不是SessionLocaleResolver实例，并且配置了interceptor.setParamName("lang");
     * 请求地址加上参数lang，前端直接报错 HTTP Status 500 – Internal Server Error
     * <p>
     * LocaleResolver是AcceptHeaderLocaleResolver实例时，header中使用Accept-Language设置语言
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        registry.addInterceptor(interceptor);
    }

    /**
     * AcceptHeaderLocaleResolver：header生效
     * SessionLocaleResolver：请求参数生效
     * 注意：如果bean name不是localeResolver，spring会加载自己的LocaleResolver实例，最终生效的也是spring的
     *
     * @return
     */
    @Bean(name = "localeResolver")
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        localeResolver.setDefaultLocale(Locale.ENGLISH);
        return localeResolver;
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(120);
        return messageSource;
    }

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean(MessageSource messageSource) {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setProviderClass(org.hibernate.validator.HibernateValidator.class);
        localValidatorFactoryBean.setValidationMessageSource(messageSource);
        return localValidatorFactoryBean;
    }
}
